package com.alliky.core.net;

import com.alliky.core.base.BaseViewModel;
import com.alliky.core.util.RxToast;

import io.reactivex.observers.DisposableObserver;

public abstract class IDisposableObserver<T> extends DisposableObserver<T> {

    BaseViewModel viewModel;

    String message = "";

    public IDisposableObserver() {
    }

    /**
     * @param viewModel 传空则不显示Loading
     */
    public IDisposableObserver(BaseViewModel viewModel) {
        this.viewModel = viewModel;
    }

    /**
     * @param viewModel 传空则不显示Loading
     * @param message   Loading提示文案
     */
    public IDisposableObserver(BaseViewModel viewModel, String message) {
        this.viewModel = viewModel;
        this.message = message;
    }

    /**
     * 成功的回调
     */
    protected abstract void onResult(T t);

    @Override
    protected void onStart() {
        super.onStart();
        if (this.viewModel != null) {
            this.viewModel.showLoading(message);
        }
    }

    @Override
    public void onComplete() {
        if (this.viewModel != null) {
            this.viewModel.hideLoading();
        }
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        if (this.viewModel != null) {
            this.viewModel.hideLoading();
        }

        if (e instanceof ResponseThrowable) {
            ResponseThrowable throwable = (ResponseThrowable) e;
            RxToast.error(throwable.message);
            return;
        } else {
            //其他全部甩锅给网络异常
            RxToast.error("网络异常");
        }
    }

    @Override
    public void onNext(T t) {
        onResult(t);
    }
}
